#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <sys/time.h>
 
#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"

//#include "user_define.h"
#include "http_server.h"
#include "datawork_jiaotong.h"
// add para lib_include
int datawork_jiaotong_init(void * sub_proc, void * para)
{
	int ret;
	// add yorself's module init func here
	return 0;
}
int datawork_jiaotong_start(void * sub_proc, void * para)
{
	int ret;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here
	while(1)
	{
		usleep(time_val.tv_usec);
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			ex_module_sendmsg(sub_proc,recv_msg);
			continue;
		}
		if((type==TYPE(HTTP_SERVER))&&(subtype==SUBTYPE(HTTP_SERVER,ACTION)))
		{
            		ret=proc_metadata_edge(sub_proc,recv_msg);
		}
        	else
			ex_module_sendmsg(sub_proc,recv_msg);
	}
	return 0;
}

int proc_metadata_edge(void * sub_proc,void * recv_msg)
{

	int ret;
	void * new_msg;
	int i;
	RECORD(HTTP_SERVER,ACTION) * event_record;
	
	ret = message_get_record(recv_msg,&event_record,0);
	if(ret<0)
		return -EINVAL;

	if(Strcmp(event_record->server_name,"http_server")==0)
	{
		Memset(event_record->server_name,0,DIGEST_SIZE);
		Strncpy(event_record->server_name,"jiaotong_server",
			DIGEST_SIZE);	
		new_msg = message_create(TYPE_PAIR(HTTP_SERVER,ACTION),
				recv_msg);
		message_add_record(new_msg,event_record);
		ex_module_sendmsg(sub_proc,new_msg);
	}
	else
		ex_module_sendmsg(sub_proc,recv_msg);
	return 0;
}

int proc_file_service_start(void * sub_proc,void * recv_msg)
{
	int ret;
	RECORD(HTTP_SERVER,ACTION) * http_cmd;
	RECORD(HTTP_SERVER,SERVER) * http_server;
	print_cubeaudit("datawork_jiaotong: http cmd exec\n");
	void * new_msg;

	http_cmd = Talloc0(sizeof(*http_cmd));
	if(http_cmd==NULL)
		return -ENOMEM;

	http_server = memdb_get_first_record(TYPE_PAIR(HTTP_SERVER,SERVER));
	if(http_server == NULL)
	{
		print_cubeerr("datawork_jiaotong: can't find http server");
		return -EINVAL;
	}

	http_cmd->server_name = dup_str(http_server->server_name,0);
	http_cmd->action = ENUM(HTTP_SERVER_ACTION,START);
	
	char user_name[DIGEST_SIZE];
	proc_share_data_getvalue("user_name",user_name);
	http_cmd->user = dup_str(user_name,DIGEST_SIZE);

	new_msg = message_create(TYPE_PAIR(HTTP_SERVER,ACTION),NULL);
	if(new_msg == NULL)
		return -EINVAL;
	message_add_record(new_msg,http_cmd);
	ex_module_sendmsg(sub_proc,new_msg);
	sleep(1);	

    	return ex_module_sendmsg(sub_proc,recv_msg);
}
